import { ISelectGroupState } from '@/entrypoints/home/components/SelectGroup'
import { yapiItemsToApiItems } from '@/entrypoints/home/utils/importer/yapiToApiItems'
import { IListItem, ImportMode } from '@/utils/interfaces'
import { useCacheStore } from '@/utils/store/cacheStore'
import { fetchApiDataBatch, fetchCatList, fetchProject } from '@/utils/yapi'
import {
    AutoComplete,
    Button,
    Form,
    Input,
    Message,
    Select,
} from '@arco-design/web-react'
import React from 'react'

export interface IImFromYapiUrlProps {
    // 预览数据
    onPreview?: (
        items: IListItem[],
        recommendGroupOptions?: Partial<ISelectGroupState>,
    ) => void
}

const ImFromYapiUrl: React.FC<IImFromYapiUrlProps> = ({ onPreview }) => {
    // 缓存
    const [importHistory, setImportHistory] = useCacheStore('importHistory', [])
    // 获取到的catList数据
    const [catOptions, setCatOptions] = useState<
        { label: string; value: string }[]
    >([])
    const [formData, setFormData] = useState<{
        url?: string
        token?: string
        projectId?: string
        selectedCatId?: string
    }>({})

    // 表单变化
    const handleFromChange = <K extends keyof typeof formData>(
        key: K,
        value: (typeof formData)[K],
    ) => {
        setFormData((prev) => {
            // url不能以/结尾
            if (key === 'url' && value && value.endsWith('/')) {
                value = value.slice(0, -1)
            }

            return { ...prev, [key]: value }
        })
    }

    // 表单变化
    const handleRequireDataChange = async () => {
        const { url, token, projectId } = formData
        if (!url || !token || !projectId) return
        const data = await fetchProject({ baseUrl: url, token, projectId })
        if (!data) return
        setCatOptions(
            data?.cat?.map((item: any) => {
                return { label: item.name, value: item._id }
            }) || [],
        )
        // 如果不在history中，则添加到history
        if (
            !importHistory?.find(
                (item) => item.url === url && item.mode === ImportMode.yapiUrl,
            )
        ) {
            setImportHistory([
                ...(importHistory || []),
                { url, mode: ImportMode.yapiUrl },
            ])
        }
    }

    // 点击导入预览
    const handleImportPreview = async () => {
        const { url, token, projectId, selectedCatId } = formData
        if (!url || !token || !projectId || !selectedCatId) {
            Message.info('请填写完整信息')
            return
        }
        const catList = await fetchCatList({
            baseUrl: url,
            token,
            catId: selectedCatId,
        })
        const apiIds = catList?.map((item: any) => item._id)
        const items = await fetchApiDataBatch({
            baseUrl: url,
            token,
            apiIds,
        })
        if (!items?.length) return
        const apiItems = await yapiItemsToApiItems(items, {
            mode: ImportMode.yapiUrl,
        })
        const catName = catOptions.find(
            (item) => item.value === selectedCatId,
        )?.label
        onPreview?.(apiItems, { addGroup: true, newGroupName: catName })
    }

    return (
        <div>
            {/* url */}
            <Form.Item label='baseUrl' rules={[{ required: true }]}>
                <AutoComplete
                    value={formData.url}
                    onChange={(value) => handleFromChange('url', value)}
                    onBlur={() => handleRequireDataChange()}
                    data={importHistory
                        ?.filter(
                            (item) => item.mode === ImportMode.swaggerJsonUrl,
                        )
                        ?.map((item) => item.url)}
                    placeholder='请输入YAPI部署的baseUrl'
                />
            </Form.Item>
            {/* token */}
            <Form.Item label='token' rules={[{ required: true }]}>
                <Input
                    value={formData.token}
                    onChange={(value) => handleFromChange('token', value)}
                    onBlur={() => handleRequireDataChange()}
                    placeholder='请输入token'
                />
            </Form.Item>
            {/* projectId */}
            <Form.Item label='projectId' rules={[{ required: true }]}>
                <Input
                    value={formData.projectId}
                    onChange={(value) => handleFromChange('projectId', value)}
                    onBlur={() => handleRequireDataChange()}
                    placeholder='请输入projectId'
                />
            </Form.Item>
            <Form.Item label='分类' rules={[{ required: true }]}>
                <Select
                    value={formData.selectedCatId}
                    onChange={(value) =>
                        handleFromChange('selectedCatId', value)
                    }
                    showSearch
                    filterOption={(input, option) => {
                        const label =
                            (option.props as any)?.children?.toString() || ''
                        return label.toLowerCase().includes(input.toLowerCase())
                    }}
                    options={catOptions}
                    placeholder='请选择分类'
                />
            </Form.Item>

            {/* 预览 */}
            <div className='flex justify-end mb-4'>
                <Button onClick={handleImportPreview}>导入预览</Button>
            </div>
        </div>
    )
}

export default ImFromYapiUrl
